<template>
  <div class="transactions-view">
    <!-- 工具栏 -->
    <div class="toolbar">
      <n-space justify="space-between">
        <n-space>
          <n-input
            v-model:value="filters.search"
            placeholder="搜索URL或方法..."
            style="width: 300px"
            clearable
          >
            <template #prefix>
              <n-icon :component="SearchOutline" />
            </template>
          </n-input>
          
          <n-select
            v-model:value="filters.method"
            placeholder="方法"
            style="width: 120px"
            clearable
            :options="methodOptions"
          />
          
          <n-select
            v-model:value="filters.statusCode"
            placeholder="状态码"
            style="width: 120px"
            clearable
            :options="statusCodeOptions"
          />
          
          <n-button @click="resetFilters">
            <template #icon>
              <n-icon :component="RefreshOutline" />
            </template>
            重置
          </n-button>
        </n-space>
      </n-space>
    </div>

    <!-- 主内容区域 -->
    <div class="content">
      <!-- 左侧请求列表 -->
      <div class="left-panel">
        <n-data-table
          :columns="columns"
          :data="filteredTransactions"
          :loading="loading"
          :pagination="false"
          :row-key="(row: HttpTransaction) => row.id"
          :row-class-name="getRowClassName"
          size="small"
          striped
          :scroll-x="800"
          :row-props="getRowProps"
          :max-height="tableHeight"
          virtual-scroll
          :item-size="40"
          :header-height="36"
          sticky-header
        />
      </div>

      <!-- 右侧详情面板 -->
      <div class="right-panel">
        <transaction-detail
          :transaction="selectedTransaction || undefined"
          @refresh="refreshTransaction"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, nextTick, h } from 'vue';
import { storeToRefs } from 'pinia';
import { type DataTableColumns } from 'naive-ui';
import SearchOutline from '@vicons/ionicons5/Search';
import RefreshOutline from '@vicons/ionicons5/Refresh';
import { useTransactionsStore } from '../stores/transactions';
import { formatTimestamp, formatStatusCode, getMethodColor, truncateText } from '../utils/format';
import { wsClient } from '../api/websocket';
import type { HttpTransaction } from '../types';
import TransactionDetail from '../components/TransactionDetail.vue';

// Store
const transactionsStore = useTransactionsStore();
const { 
  transactions, selectedTransaction, loading, filteredTransactions
} = storeToRefs(transactionsStore);
const { filters } = transactionsStore;

// 虚拟滚动相关状态
const tableHeight = ref(600); // 表格高度

// 筛选选项
const methodOptions = [
  { label: 'GET', value: 'GET' },
  { label: 'POST', value: 'POST' },
  { label: 'PUT', value: 'PUT' },
  { label: 'DELETE', value: 'DELETE' },
  { label: 'PATCH', value: 'PATCH' },
  { label: 'HEAD', value: 'HEAD' },
  { label: 'OPTIONS', value: 'OPTIONS' }
];

const statusCodeOptions = [
  { label: '200', value: '200' },
  { label: '201', value: '201' },
  { label: '204', value: '204' },
  { label: '301', value: '301' },
  { label: '302', value: '302' },
  { label: '304', value: '304' },
  { label: '400', value: '400' },
  { label: '401', value: '401' },
  { label: '403', value: '403' },
  { label: '404', value: '404' },
  { label: '500', value: '500' },
  { label: '502', value: '502' },
  { label: '503', value: '503' }
];

// 表格列定义
const columns: DataTableColumns<HttpTransaction> = [
  {
    title: '索引',
    key: 'index',
    width: 60,
    render: (_, index) => index + 1
  },
  {
    title: '方法',
    key: 'method',
    width: 70,
    render: (row) => {
      return h('span', {
        style: {
          color: getMethodColor(row.request.method),
          fontWeight: 'bold',
          fontSize: '12px'
        }
      }, row.request.method);
    }
  },
  {
    title: 'URL',
    key: 'url',
    minWidth: 250,
    ellipsis: {
      tooltip: true
    },
    render: (row) => h('span', {
      style: { fontSize: '12px' }
    }, truncateText(row.request.url, 60))
  },
  {
    title: 'Client HTTP',
    key: 'clientHttpVersion',
    width: 100,
    render: (row) => h('span', {
      style: { fontSize: '12px' }
    }, row.request.clientHttpVersion || 'HTTP/1.1')
  },
  {
    title: 'Remote HTTP',
    key: 'remoteHttpVersion',
    width: 100,
    render: (row) => h('span', {
      style: { fontSize: '12px' }
    }, row.request.remoteHttpVersion || '-')
  },
  {
    title: '状态码',
    key: 'statusCode',
    width: 80,
    render: (row) => {
      if (!row.response) return '-';
      const status = formatStatusCode(row.response.statusCode);
      return h('n-tag', {
        type: status.type,
        size: 'small',
        style: { fontSize: '11px' }
      }, status.text);
    }
  },
  {
    title: '时间',
    key: 'timestamp',
    width: 150,
    render: (row) => h('span', {
      style: { fontSize: '12px' }
    }, formatTimestamp(row.request.timestamp))
  },
  {
    title: '耗时',
    key: 'duration',
    width: 70,
    render: (row) => h('span', {
      style: { fontSize: '12px' }
    }, row.duration ? `${row.duration}ms` : '-')
  }
];

// 现在使用 store 中的 filteredTransactions 计算属性

// 方法
function resetFilters() {
  transactionsStore.resetFilters();
}

// 清空功能已移至App.vue中统一处理

function refreshTransaction(id: string) {
  transactionsStore.fetchTransactionDetail(id);
}

function getRowClassName(row: HttpTransaction) {
  if (selectedTransaction.value?.id === row.id) {
    return 'selected-row';
  }
  return '';
}

function getRowProps(row: HttpTransaction) {
  return {
    style: 'cursor: pointer;',
    onClick: () => {
      console.log('点击了行:', row.id); // 调试日志
      transactionsStore.selectTransaction(row);
    }
  };
}

// 计算表格高度
function calculateTableHeight() {
  nextTick(() => {
    const viewportHeight = window.innerHeight;
    // 减去工具栏和其他元素的高度
    tableHeight.value = Math.max(400, viewportHeight - 180);
  });
}

// 键盘导航
function handleKeyDown(event: KeyboardEvent) {
  // 检查是否有输入框聚焦
  const activeElement = document.activeElement as HTMLElement;
  if (activeElement && (
    activeElement.tagName === 'INPUT' || 
    activeElement.tagName === 'TEXTAREA' || 
    activeElement.contentEditable === 'true'
  )) {
    return; // 有输入框聚焦时不处理键盘导航
  }
  
  if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
    event.preventDefault();
    
    if (filteredTransactions.value.length === 0) return;
    
    const currentIndex = selectedTransaction.value 
      ? filteredTransactions.value.findIndex(t => t.id === selectedTransaction.value!.id)
      : -1;
    
    let newIndex = currentIndex;
    
    if (event.key === 'ArrowUp') {
      newIndex = currentIndex > 0 ? currentIndex - 1 : filteredTransactions.value.length - 1;
    } else if (event.key === 'ArrowDown') {
      newIndex = currentIndex < filteredTransactions.value.length - 1 ? currentIndex + 1 : 0;
    }
    
    if (newIndex >= 0 && newIndex < filteredTransactions.value.length) {
      transactionsStore.selectTransaction(filteredTransactions.value[newIndex]);
    }
  }
}

// 生命周期
onMounted(() => {
  // 计算表格高度
  calculateTableHeight();
  
  // 监听窗口大小变化
  window.addEventListener('resize', calculateTableHeight);
  
  // 添加键盘事件监听
  document.addEventListener('keydown', handleKeyDown);
});

onUnmounted(() => {
  // 移除窗口监听
  window.removeEventListener('resize', calculateTableHeight);
  
  // 移除键盘事件监听
  document.removeEventListener('keydown', handleKeyDown);
});
</script>

<style scoped lang="less">
.transactions-view {
  height: 100%;
  display: flex;
  flex-direction: column;
  
  .toolbar {
    padding: 16px 20px;
    background: var(--bg-color);
    border-bottom: 1px solid var(--border-color);
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
  }
  
  .content {
    flex: 1;
    display: flex;
    overflow: hidden;
    gap: 1px;
    background: var(--border-color);
    
    .left-panel {
      width: 60%;
      background: var(--bg-color);
      overflow: hidden;
      display: flex;
      flex-direction: column;
    }
    
    .right-panel {
      width: 40%;
      background: var(--bg-color);
      overflow: hidden;
    }
  }
}

:deep(.selected-row) {
  background-color: #e6f7ff !important;
  
  .n-data-table-td {
    background-color: #e6f7ff !important;
  }
}

:deep(.n-data-table) {
  height: 100%;
  
  .n-data-table-wrapper {
    height: 100%;
  }
  
  .n-data-table-base-table {
    height: 100%;
  }
  
  // 虚拟滚动优化
  .n-data-table-thead {
    position: sticky !important;
    top: 0 !important;
    z-index: 2 !important;
    background: #fafafa !important;
  }
  
  .n-virtual-list {
    height: 100% !important;
  }
}

:deep(.n-data-table-td) {
  padding: 8px 12px !important;
  font-size: 12px;
  line-height: 1.4;
}

:deep(.n-data-table-th) {
  padding: 10px 12px !important;
  background: #fafafa !important;
  font-weight: 600;
  font-size: 12px;
  color: #333 !important;
}

:deep(.n-input) {
  border-radius: 6px;
}

:deep(.n-select) {
  border-radius: 6px;
}

:deep(.n-button) {
  border-radius: 6px;
  font-weight: 500;
}
</style> 